package com.func.domain.strategy.service.rule.chain.impl;

import com.func.domain.strategy.repository.IStrategyRepository;
import com.func.domain.strategy.service.armory.IStrategyDispatch;
import com.func.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.func.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import com.func.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName RuleWeightLogicChain
 * @Description 抽奖责任链-权重抽奖
 * @Author: func
 * @Date 2025/2/28 12:45
 * @Version 1.0
 */

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    IStrategyRepository repository;

    @Resource
    IStrategyDispatch strategyDispatch;

    @Override
    public DefaultLogicChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);

        // 获取到所有的权重值, 并逆序排序
        List<Long> ruleValueKeyGroup = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(ruleValueKeyGroup, Collections.reverseOrder());

        // 找到当前用户积分处于什么范围内
        Integer useScore = repository.queryActivityAccountTotalUserCount(userId, strategyId);
        Long nextValue =  ruleValueKeyGroup.stream()
                .filter(ruleVale -> useScore >= ruleVale)
                .findFirst()
                .orElse(null);

        // 非放行结果, 成功找到了当前积分在的范围, 执行过滤
        if (null != nextValue) {
            String ruleWeightKey = analyticalValueGroup.get(nextValue);
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, ruleWeightKey);
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultLogicChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        // 放行, 进行下一步的过滤
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {} ", userId, strategyId, ruleModel());
        return this.next().logic(userId, strategyId);
    }
    @Override
    public String ruleModel() {
        return DefaultLogicChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    /**
     * 将获取到的ruleValue 4000:100,101,102转化为4000 -> 4000:100,101,102的Map返回
     * @param ruleValue rule_weight的rule_value
     * @return 4000 -> 4000:100,101,102的Map
     */
    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroup = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroup) {
            // 检查输入是否为空
            if (null == ruleValueKey || ruleValueKey.isEmpty())
                return ruleValueMap;

            String[] splitRuleValue = ruleValueKey.split(Constants.COLON);
            if (splitRuleValue.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format " + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(splitRuleValue[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
